const ws = require("nodejs-websocket")
const { util } = require('../util/util')

// 将客户端添加到用户池
function addUser(connection) {
  let client = util.ws.userPool.find(item => item.userId === connection.key);
  if (client !== undefined) return console.log(`Add new User`);
  else util.ws.userPool.push({ userId: connection.key, client: connection, sdp: null });
}
// 将客户端从用户池中去除
function kickUser(id) {
  let index = 0
  for (let item of util.ws.userPool) {
    if (`${item.userId}` === id) {
      util.ws.userPool.splice(index, 1)
      break
    }
    index += 1
  }
}
// 发送消息给特定的客户端
function sendMsg(id, msg) {
  let client = util.ws.userPool.find(item => item.userId === id);
  if (client === undefined) return console.log(`sendMsg() can't find the user ${id}`);
  else client.client.sendText(msg);
}

// 设置客户端的SDP
function setSDP(id, sdp) {
  let client = util.ws.userPool.find(item => item.userId === id);
  if (client === undefined) return console.log(`setSDP() can't find the user ${id}`);
  else client.sdp = sdp;
}

// 获取客户端的SDP
function getSDP(id) {
  let client = util.ws.userPool.find(item => item.userId === id);
  return client === undefined ? false : client.sdp
}

let service = {
  /**
   * @function /websocket/startWebSocket
   * @type GET
   * @returns { result } 
   */
  async startWebSocket() {
    try {
      if (util.ws.isWebSocketOn === false) {
        let server = ws.createServer(function(connection) {
          // 如果客户端不存在, 新增客户端, 添加连接池
          addUser(connection)
            // 把client自己的key发给client, 用于发起RTC
          connection.sendText(connection.key)

          connection.on("text", function(str) {
            if (JSON.parse(str) instanceof Object) {
              // RTC连接过程, 关键字参考流程文档
              let rtc = JSON.parse(str);
              switch (rtc.type) {
                case 'offer':
                  // 此处设置的rtc.sdp是对象, 不是对象字符串
                  setSDP(connection.key, rtc.sdp)
                  break;
                case 'id':
                  // 将创建方的SDP(Offer)发给加入方
                  sendMsg(connection.key, JSON.stringify({ type: 'offer', sdp: getSDP(rtc.id) }));
                  break;
                case 'answer':
                  // 将加入方的SDP(Answer)发给创建方
                  sendMsg(rtc.id, JSON.stringify({ type: 'answer', sdp: rtc.sdp }));
                  break;
                case 'close':
                  // 加入方告知创建方将RTC连接关闭
                  sendMsg(rtc.id, JSON.stringify({ type: 'close' }));
                  break;
                default:
                  console.log("unknown msg");
                  break;
              }
            }
          });

          connection.on("close", function() {
            kickUser(connection.key);
            //客户端关闭
          });

          connection.on("error", function() {
            kickUser(connection.key);
            //error
          });
        })
        server.listen(5273, "0.0.0.0", () => {
          util.ws.isWebSocketOn = true;
        });
        return util.msgFormatter([], `WS启动成功`, 200)
      } else return util.msgFormatter([], `WS已启动`, 304)
    } catch (e) {
      console.log('WS error: ', e);
    }
    return util.msgFormatter([], `WS启动失败`, 403)
  }
}

module.exports = service